package com.skynet.supervision.aop.validate;

import lombok.val;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;
import java.util.regex.Pattern;

public class PhoneValidator implements ConstraintValidator<Phone, String> {

    // 严格模式: 编辑日期:2020-11-17,尽可能的满足编辑日期之前的手机号段
    public static final Pattern mobilePattern = Pattern.compile("^1(3([0-35-9]\\d|4[1-8])" +
            "|4[14-9]\\d" +
            "|5([01235689]\\d|7[1-79])" +
            "|66\\d" +
            "|7[1-35-8]\\d" +
            "|8\\d{2}|9[13589]\\d)\\d{7}$");

    // 非严格模式:
    // 1. 只要是1开头+10个数字,就认为是手机号
    // 2. 以 "v-"开头, 后连接 17 个常规字符([a-z][A-Z][0-9_])
    public static final Pattern simplePattern = Pattern.compile("(v-\\w{17})|(1\\d{10})");

    private Phone anno;

    @Override
    public void initialize(Phone constraintAnnotation) {
        anno = constraintAnnotation;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        Objects.requireNonNull(anno);
        if (anno.required() && value == null) {
            return false;
        }
        if (value != null) {
            val curPattern = anno.strict() ? mobilePattern : simplePattern;
            return curPattern.matcher(value).matches();
        }
        return true;
    }
}
